Skip to main content

什么是高阶组件 HOC?

高阶组件就是一个函数,且该函数接受一个组件作为参数,并返回一个新的组件。

举例说明即可:

  1. React.forwardRef
  2. React-Redux 的 connect
  3. React-Router 的 withRouter

怎么用

预览地址

import React from "react";

// 高阶组件
function withMouse(WrappedComponent) {
class Mouse extends React.Component {
state = {
x: 0,
y: 0
};
// 鼠标移动事件的事件处理程序
handleMouseMove = (e) => {
this.setState({
x: e.clientX,
y: e.clientY
});
};
// 监听鼠标移动事件
componentDidMount() {
window.addEventListener("mousemove", this.handleMouseMove);
}
// 推荐:在组件卸载时移除事件绑定
componentWillUnmount() {
window.removeEventListener("mousemove", this.handleMouseMove);
}
render() {
// return this.props.render(this.state)
// 在render函数里返回参数组件,把当前组件的状态设置进去,参数组件就可以通过props接收到当前类组件中复用的状态
return <WrappedComponent {...this.state} {...this.props} />;
}
}
return Mouse;
}

// 子组件
// 在参数组件里可以通过props接收到函数的类组件中复用的状态
function Position(props) {
return (
<p>
鼠标位置:{props.x} {props.y}
</p>
);
}

// 高阶组件:把 position子组件进行包装
let MousePosition = withMouse(Position);

const App = () => {
return (
<div>
原组件:
<Position />
高阶组件:
{/*相当于给高阶组件的类组件Mouse添加的props*/}
<MousePosition a="1" />
</div>
);
};

export default App;

HOC 的优缺点

优点 ∶ 逻辑服用、不影响被包裹组件的内部逻辑。 缺点 ∶ hoc 传递给被包裹组件的 props 容易和被包裹后的组件重名,进而被覆盖

参考文章